// pages/choiceProject/index.js
import axios from '../network/index'
const md5 = require("../../utils/md5")
import {
  fileUrl
} from "../network/index"
var _this;
var projectLoading = false;
var projectLoading2 = false;
var loading = false;
let timer;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nameTypeList: ['装修', '空调', '采暖', '净水', '新风', '弱电'],
    nameType: '',
    UpOrDown: false,
    showClose: false,
    spaceText: "加载中...",
    spaceTexts: "加载中...",
    spaceTexts2: "加载中...",
    showMore: false,
    showTime: false,
    unfold: false,
    unfold2: false,
    currentDate: new Date().getTime(),
    // minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      } else if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    projectData: [],
    projectDataCopy: [],
    projectDataCopy2: [],
    selectProject: {},
    selectProject2: {},
    taskNumber: [{
      number: 1,
      selectMaterialsLable: "",
      selectMaterialsValue: "",
      price: '',
      unitPrice: '',
      image: [],
      seletctMaterialsStatus: false,
      currentIndex: 0
    }],
    materials: [],
    materialsCopy: [],
    modal: false,
    inventoryPicture: [],
    estimatedTime: '',
    array: [],
    purchaseUserId: ""
  },
  nameTypeChange(e) {
    this.setData({
      nameType: e.detail.value,
      UpOrDown: false
    })
    this.saveCache()
  },
  catchNameType() {
    this.setData({
      UpOrDown: true
    })
  },
  cancelSelectNameType() {
    this.setData({
      UpOrDown: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setStorageSync('spaceData', this.data)
    _this = this
    this.getProject()
    this.getBank()
    this.getMaterials()
    this.getChaseIdList()
    let saveCache = wx.getStorageSync('saveCacheTwo')
    //使用md5验证数据是否一样
    let cache = md5.hexMD5(JSON.stringify(saveCache))
    let beforeDate = md5.hexMD5(JSON.stringify(this.data))
    //拿取初始的的data数据
    let _this = this
    if (saveCache != '') {
      if (cache != beforeDate) {
        wx.showModal({
          title: "提示",
          content: "检测到上次有未提交的数据，是否恢复！",
          success(res) {
            if (res.confirm) {
              if (saveCache.taskNumber && saveCache.taskNumber.length > 0) {
                saveCache.taskNumber.forEach(item => {
                  item.seletctMaterialsStatus = false
                })
              }
              _this.setData({
                ...saveCache
              })
            } else {}
            wx.removeStorageSync('saveCacheTwo')
          }
        })
      }
    }
  },
  //保存缓存
  saveCache() {
    let data = this.data
    wx.setStorageSync('saveCacheTwo', data)
  },
  memoIpt(e) {
    this.setData({
      memo: e.detail
    })
  },
  openSelectTime() {
    this.setData({
      showTime: true
    })
  },
  offSelectTime() {
    this.setData({
      showTime: false
    })
  },
  bindPickerChange(e) {
    this.setData({
      index: e.detail.value,
      purchaseUserId: this.data.array[e.detail.value].userId
    })
    this.saveCache()
  },
  prePicture(e) {
    let img = e.currentTarget.dataset.img
    wx.previewImage({
      current: img,
      urls: [img],
    })
  },
  //确认时间
  confirmTime(e) {
    this.setData({
      currentDate: e.detail,
      estimatedTime: this.format(e.detail)
    })
    this.offSelectTime()
    this.saveCache()
  },
  add0(m) {
    return m < 10 ? '0' + m : m
  },
  format(e) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(e);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    return y + '-' + this.add0(m) + '-' + this.add0(d)
  },
  //项目搜索的值
  projectIpt(e) {
    if (projectLoading) return
    let val = e.detail
    let list = this.data.projectDataCopy
    if (!val) {
      this.setData({
        projectData: list,
      })
    } else {
      let projectData = list.filter(item => item.projectName.indexOf(val) > -1)
      this.setData({
        projectData,
        spaceTexts: projectData && projectData.length > 0 ? '' : '暂无数据',
        unfold: true
      })
    }
    this.saveCache()
  },
  projectIpt2(e) {
    if (projectLoading2) return
    let val = e.detail
    let list = this.data.projectDataCopy2
    if (!val) {
      this.setData({
        projectData2: list,
      })
    } else {
      let projectData2 = list.filter(item => JSON.stringify(item).includes(val))
      this.setData({
        projectData2,
        spaceTexts2: projectData2 && projectData2.length ? '' : '暂无数据',
        unfold2: true
      })
    }
    this.saveCache()
  },
  getProject() {
    axios({
      url: "/api/reimbursed/getProjecAllData",
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
    }).then(v => {
      this.setData({
        projectData: v.data,
        projectDataCopy: v.data
      })
    })
  },
  getBank(val = '') {
    axios({
      url: '/supplierBackCard',
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        userId: wx.getStorageSync('userId'),
        searchVal: val,
      }
    }).then(v => {
      this.setData({
        projectData2: v.data.content,
        projectDataCopy2: v.data.content
      })
    })
  },
  confirmSelect() {
    this.setData({
      unfold: !this.data.unfold
    })
  },
  confirmSelect2() {
    this.setData({
      unfold2: !this.data.unfold2
    })
  },
  openProjectList() {
    projectLoading = false
    this.setData({
      unfold: true
    })
  },
  openProjectList2() {
    projectLoading2 = false
    this.setData({
      unfold2: true
    })
  },
  //项目下拉获取选中的值
  currentValue(e) {
    projectLoading = true
    this.setData({
      selectProject: e.currentTarget.dataset,
      unfold: false
    })
    this.saveCache()
  },
  currentValue2(e) {
    projectLoading2 = true
    this.setData({
      selectProject2: e.currentTarget.dataset,
      unfold2: false
    })
    this.saveCache()
  },

  //清楚输入的项目搜索值
  clearProject() {
    this.setData({
      'selectProject.name': ''
    })
  },
  clearProject2() {
    this.setData({
      selectProject2: {}
    })
  },
  //选择变化事件
  numChange(e) {
    var list = this.data.taskNumber
    var index = e.currentTarget.dataset.index
    list[index].number = e.detail;
    this.setData({
      taskNumber: list
    })
    this.saveCache()
  },
  //删除该任务
  delTask(e) {
    let _this = this
    let currentDelTask = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    wx.showModal({
      title: '提示',
      content: "是否删除该任务",
      success(res) {
        if (res.confirm) {
          wx.showToast({
            title: '删除成功',
          })

          let newtaskNumber = taskNumber.filter((item, index) => currentDelTask != index)
          _this.setData({
            taskNumber: newtaskNumber
          })
          _this.saveCache()
        } else {
          wx.showToast({
            title: '取消删除',
            icon: "none",
          })
        }
      }
    })
  },
  //获取科目
  getMaterials() {
    this.setData({
      spaceText: "数据加载中..."
    })
    axios({
      url: "/api/reimbursed/getMaterialAllData",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
    }).then(v => {
      this.setData({
        materials: v.data,
        materialsCopy: JSON.parse(JSON.stringify(v.data)),
        spaceText: v.data && v.data.length > 0 ? '' : '暂无数据'
      })
    }).catch(V => {
      wx.showToast({
        title: V,
        icon: "none"
      })
    })
  },
  //打开科目搜索框/搜索框聚焦事件
  openSelectList(e) {
    loading = false
    let taskNumber = this.data.taskNumber
    taskNumber.forEach(item => {
      item.seletctMaterialsStatus = false
    })
    this.setData({
      taskNumber,
      materials: this.data.materialsCopy
    })
  },

  //搜素科目Input事件
  searchMaterials(e) {
    if (loading) return
    let v = e.detail.value
    let i = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    let materialsCopy = this.data.materialsCopy
    if (!v) {
      this.setData({
        materials: list,
        [`taskNumber[${i}].seletctMaterialsStatus`]: false,
        [`taskNumber[${i}].selectMaterialsValue`]: '',
        [`taskNumber[${i}].selectMaterialsLable`]: '',
        [`taskNumber[${i}].img`]: '',
      })
      return
    }
    let list = materialsCopy.filter(item => item.materialName.indexOf(v) > -1)
    clearTimeout(timer)
    timer = setTimeout(() => {
      this.setData({
        materials: list,
        spaceText: list && list.length > 0 ? '' : '暂无数据'
      })
      if (!taskNumber[i].seletctMaterialsStatus) {
        this.setData({
          [`taskNumber[${i}].seletctMaterialsStatus`]: true,
        })
      }

    }, 20);
  },
  //点击图标打开或关闭下拉框
  confirmMaterials(e) {
    let index = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    if (!taskNumber[index].seletctMaterialsStatus) {
      taskNumber.forEach(item => {
        item.seletctMaterialsStatus = false
      })
      taskNumber[index].seletctMaterialsStatus = true
      this.setData({
        taskNumber,
        materials: this.data.materialsCopy
      })
    } else {
      this.setData({
        [`taskNumber[${index}].seletctMaterialsStatus`]: !taskNumber[index].seletctMaterialsStatus,
      })
    }
  },

  //选择科目
  currentMaterialsV(e) {
    loading = true
    let taskNumber = this.data.taskNumber
    let data = e.currentTarget.dataset.data
    let index = e.currentTarget.dataset.fatherindex
    taskNumber[index].selectMaterialsLable = data.materialName
    taskNumber[index].selectMaterialsValue = data.materialCode
    taskNumber[index].price = data.materialDefaultAmout || 0
    taskNumber[index].number = 1
    taskNumber[index].unitPrice = data.materialDefaultAmout || 0
    taskNumber[index].img = data.img
    taskNumber[index].brand = data.brand
    taskNumber[index].stockNum = data.stockNum
    taskNumber[index].unit = data.unit
    this.setData({
      [`taskNumber[${index}]`]: taskNumber[index],
      [`taskNumber[${index}].seletctMaterialsStatus`]: false
    })
    this.saveCache()
  },
  //打开详情弹窗
  openDetail(e) {
    let data = e.currentTarget.dataset.data
    this.setData({
      showDetail: true,
      detailInfo: data
    })
  },
  //关闭详情弹窗
  closeDetail() {
    this.setData({
      showDetail: false,
    })
  },
  // 添加任务
  addTask() {
    let taskNumber = this.data.taskNumber
    taskNumber.push({
      number: 1,
      price: '',
      unitPrice: '',
      selectMaterialsLable: '',
      selectMaterialsValue: '',
      firstchoice: false,
      seletctMaterialsStatus: false
    })
    this.setData({
      taskNumber
    })
    this.saveCache()
  },

  //删除图
  delPicture(e) {
    //获取图片的下标
    let {
      index,
    } = e.currentTarget.dataset
    let _this = this
    wx.showModal({
      title: "提示",
      content: "是否删除图片",
      success(res) {
        if (res.confirm) {
          let inventoryPicture = _this.data.inventoryPicture.filter((item, i) => {
            return !(index == i)
          })
          _this.setData({
            inventoryPicture
          })
          wx.showToast({
            title: '删除成功',
          })
          _this.saveCache()
        }
      }
    })
  },
  preview(e) {
    // 预览图片
    //该任务的下标
    let type = e.currentTarget.dataset.type
    let previewUrl = e.currentTarget.dataset.image.url
    let file = e.currentTarget.dataset.image.fileType
    if (file != 'image') {
      wx.showLoading({
        title: '正在打开文件',
      })
      wx.downloadFile({
        url: previewUrl,
        success: (res) => {
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              wx.hideLoading({
                success: (res) => {},
              })
            },
            fail: function (v) {
              wx.showToast({
                title: '打开文件失败，请重试 ',
                icon: "none",
              })
            }
          })
        }
      })
    } else {
      let urls = this.data.inventoryPicture
      let urlsDate = urls.map(v => {
        return v.url
      })
      wx.previewImage({
        current: previewUrl,
        urls: urlsDate
      })
    }
  },

  //上传图片
  pricture(e) {
    this.setData({
      modal: false
    })

    let type = this.data.type
    let _this = this
    let inventoryPicture = this.data.inventoryPicture
    //保存本地预览图

    wx.chooseImage({
      count: 10,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],

      complete(e) {

      },
      success(res) {

        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFiles
        //获取文件大小
        let ratio = 80
        tempFilePaths.forEach(element => {
          if (element.size > 20971520) {
            wx.showToast({
              title: '图片限制为20M',
              icon: "none",
            })
            return
          } else if (element.size > 10485760)
            ratio = 10
          else if (element.size > 5242880 && element.size < 10485760) {
            ratio = 20
          }
          //压缩图片，只能在真机上使用，模拟器不支持

          wx.compressImage({
            src: element.path,
            quality: ratio,
            success: function (res) {
              wx.showLoading({
                title: '图片上传中...',
                mask: true
              })
              wx.uploadFile({
                filePath: res.tempFilePath,
                name: 'img',
                url: fileUrl,
                success: function (v) {
                  wx.hideLoading({
                    success: (res) => {},
                  })

                  if (v.statusCode != 200) {
                    wx.showToast({
                      icon: "none",
                      title: '图片上传失败',
                    })
                    return
                  }
                  let imageUrl = JSON.parse(v.data).data
                  inventoryPicture.push({
                    url: imageUrl,
                    type: 1,
                    fileType: 'image'
                  })
                  _this.setData({
                    inventoryPicture
                  })
                  _this.saveCache()
                },
                fail: function () {
                  wx.showToast({
                    title: '图片上传失败',
                    icon: "none",
                  })
                }
              })
            },
            fail: function (v) {
              wx.showToast({
                title: '图片压缩失败',
                icon: "none",
              })
            }
          })
        })
      },
      fail: function (v) {
        wx.showToast({
          title: '打开相机失败',
          icon: "none",
        })
      }
    })
  },

  uploadFile() {
    this.setData({
      modal: false
    })
    let type = this.data.type
    let _this = this
    let inventoryPicture = this.data.inventoryPicture

    wx.chooseMessageFile({
      type: "file",
      count: 10,
      extension: app.globalData.extension,
      success: (v) => {
        wx.showLoading({
          title: '文件上传中...',
          mask: true
        })
        v.tempFiles.forEach(item => {
          let suffixArray = item.name.split('.')
          let suffix = suffixArray[suffixArray.length - 1]

          wx.uploadFile({
            filePath: item.path,
            name: 'img',
            url: fileUrl,
            success: (v) => {
              wx.hideLoading({
                success: (res) => {},
              })
              if (v.statusCode != 200) {
                wx.showToast({
                  title: '文件上传失败！',
                  icon: "none",
                })
                return
              }
              let file = JSON.parse(v.data).data
              inventoryPicture.push({
                url: file,
                type: 1,
                fileType: suffix
              })
              _this.setData({
                inventoryPicture
              })
              _this.saveCache()
            }
          })
        })
      }
    })
    this.saveCache()
  },
  //上传文件
  modal(e) {
    let type = e.currentTarget.dataset.type
    this.setData({
      modal: true,
      type
    })
  },
  cancel() {
    this.setData({
      modal: false,
    })
  },

  // 图片预览
  prevImg(e) {
    let index = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    let urls = taskNumber.map(item => item.img)
    wx.previewImage({
      current: taskNumber[index].img,
      urls,
    })
  },
  //获取采购人员列表
  getChaseIdList() {
    axios({
      url: "/api/user/purchaseList",
      method: "post",
    }).then(res => {
      if (res.code == 200) {
        // let array = res.data.content.map(item => item.name)
        this.setData({
          array: res.data.content
        })
      }
    })
  },

  //提交报销
  submitTask() {
    let taskNumber = this.data.taskNumber
    if (Object.keys(this.data.selectProject).length == 0) {
      wx.showToast({
        title: "请选择项目！",
        icon: "none",
      })
      return
    }
    if (Object.keys(this.data.selectProject2).length == 0) {
      wx.showToast({
        title: "请选择收款账户！",
        icon: "none",
      })
      return
    }
    if (!this.data.nameType) {
      wx.showToast({
        title: "请选择类别",
        icon: "none",
      })
      return
    }
    if (!this.data.estimatedTime) {
      wx.showToast({
        title: "到货时间不能为空",
        icon: "none",
      })
      return
    }
    if (!this.data.purchaseUserId) {
      wx.showToast({
        title: "请选择采购人员",
        icon: "none",
      })
      return
    }
    var flag = true
    if (taskNumber && taskNumber.length > 0) {
      taskNumber.forEach(item => {
        if (!item.selectMaterialsValue) flag = false
      })
    }
    if (!flag) {
      wx.showToast({
        title: '检测到不正确的科目选择！请检查！',
        icon: "none",
        duration: 1500
      })
      return
    }
    wx.showLoading({
      title: '提交中...',
    })
    let materialData = taskNumber.map(v => {
      return {
        materialCode: v.selectMaterialsValue,
        num: v.number
      }
    })
    let _this = this
    axios({
      url: "/demandApply/submit",
      method: 'POST',
      data: {
        imgs: [...this.data.inventoryPicture.map(item => item.url)],
        estimatedTime: this.data.estimatedTime,
        materialData,
        projectCode: this.data.selectProject.key,
        userId: wx.getStorageSync('userId'),
        purchaseUserId: this.data.purchaseUserId,
        memo: this.data.memo,
        sourceName: this.data.nameTypeList[this.data.nameType],
        backCardName: this.data.selectProject2.v,
        backCardNumber: this.data.selectProject2.key,
        supplierName: this.data.selectProject2.name,
      },
    }, 'application/json').then(v => {
      wx.hideLoading({
        success: (res) => {},
      })
      if (v.code == 200) {
        wx.removeStorageSync('saveCacheTwo')
        wx.showToast({
          title: v.msg,
        })
        wx.navigateBack({
          delta: 1,
        })
      } else {
        wx.showToast({
          icon: "none",
          title: v.error || v.msg,
        })
      }
    }).catch(v => {
      wx.hideLoading({
        success: (res) => {},
      })
      wx.showToast({
        icon: 'none',
        title: v,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    this.onLoad()

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
})